package com.wimcorp.magic.client.input;

import java.rmi.RemoteException;
import java.util.Set;
import java.util.concurrent.Callable;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.lang.StringUtils;
import org.fusesource.jansi.Ansi.Color;

import com.wimcorp.magic.client.CommandLineInterface;
import com.wimcorp.magic.exception.SystemException;
import com.wimcorp.magic.input.Target;
import com.wimcorp.magic.input.Type;
import com.wimcorp.magic.userinterface.GameInterface;

public class AbilitySelector extends Selector implements Callable<Long> {

	public AbilitySelector(CommandLineInterface commandLineInterface) {
		super(commandLineInterface);
	}

	@Override
	public Long call() {
		return select();
	}

	private long select() {
		Options options = getSelectAbilityOptions();
		String message = "Select an ability. ";
		ConsoleInput selectConsole = new ConsoleInput();
		ConsoleInput mainConsole = getCommandLineInterface().getMainConsole();
		CommandLineParser parser = new DefaultParser();
		Long result = null;
		setRun(true);
		while (isRun()) {
			mainConsole.cancel();
			getCommandLineInterface().printInstruction(message);
			try {
				CommandLine line = parser.parse(options, selectConsole.readLine().split(" "));
				for (Option option : line.getOptions()) {
					if ("s".equals(option.getOpt())) {
						result = execute(option);
					} else {
						result = processCommands(options, line.getOptions());
					}
				}
			} catch (Exception e) {
				getCommandLineInterface().print(e.getMessage(), Color.RED);
			}
		}
		synchronized (mainConsole.getLock()) {
			mainConsole.getLock().notifyAll();
		}
		return result;
	}

	private Long execute(Option option) throws RemoteException, SystemException {
		Long result = null;
		String input = option.getValue();
		String playerName = getCommandLineInterface().getPlayerName();
		GameInterface game = getCommandLineInterface().getGame();
		String opponentName = game.getOpponent(playerName);
		if (StringUtils.isNumeric(input)) {
			long identifier = new Long(input);
			result = game.validateAbilityInput(playerName, identifier);
		}
		if (result == -1) {
			throw new SystemException(String.format("No ability with %s found. ", input));
		}
		setRun(false);
		return result;

	}

	public Options getSelectAbilityOptions() {
		Options options = new Options();
		options.addOption(getHelpOption());
		options.addOption(getDoneOption());
		options.addOption(getSelectOption());
		options.addOption(getPlayerListOption());
		options.addOption(getViewBattleFieldOption());
		options.addOption(getViewGraveyardOption());
		options.addOption(getViewHandOption());
		options.addOption(getViewLifeOption());
		return options;
	}

}
